# -*- coding: utf-8 -*-

from PyQt4 import QtCore
from PyQt4.QtCore import QString
from PyQt4 import QtGui
from questionWidgetGui import Ui_questionWidget
from answers import Answers
from answerWidgets import PercentWidget
import platform

class Question(QtGui.QWidget):

    def __init__(self, title=None, answers=None, type=None, addButton=True):
        super(Question, self).__init__(None)
        # titulek otazky, volitelny, nemusi byt
        self.title = title
        # text(zadani) otazky, povinne
        #self.text = None
        # odpovedi
        self.answers = Answers()
        # typ, vyuziva se hlavne pri otevirani otazek ze souboru
        # TODO by tu ani nemuselo byt ne ?
        self.type = type
        # drzi nastaveni (ne)zaskrtnuti otazky v GUI
        self.checked = False
        self.errors = []

        # UI widgetu s otazkou
        self.ui = Ui_questionWidget()
        self.ui.setupUi(self)

        self.deleteButtonMapper = QtCore.QSignalMapper(self)
        self.connect(self.deleteButtonMapper, QtCore.SIGNAL("mapped(int)"), self, QtCore.SIGNAL("deleteAnswerRow(int)"))
        self.connect(self, QtCore.SIGNAL("deleteAnswerRow(int)"), self.deleteAnswerRow)


    def __repr__(self):
        return "<%s %s>" % (self.objectName(), id(self))


    def addAnswer(self, data=None):
        answerWidgets = self.answers.getAnswer()
        if data:
            answer = []
            answerPair = zip(answerWidgets, data)
            #print answerPair
            # nastavime widgetu prirazenou hodnotu = data
            for pair in answerPair:
                widget, value = pair[0], pair[1]
                widget.setValue(value)
                answer.append(widget)
        else:
            answer = answerWidgets
        for column, widget in enumerate(answer):
            if isinstance(widget, PercentWidget):
                self.connect(widget.percentBox, QtCore.SIGNAL("editTextChanged(const QString &)"), self.validatePercent)
            self.ui.answersLayout.addWidget(widget, self.answers.rowCount, column)
        # mazaci tlacitko
        deleteButton = self.answers.deleteButton()
        self.deleteButtonMapper.setMapping(deleteButton, self.answers.rowCount)
        self.connect(deleteButton, QtCore.SIGNAL("clicked()"), self.deleteButtonMapper, QtCore.SLOT("map()"))
        self.ui.answersLayout.addWidget(deleteButton, self.answers.rowCount, len(answer)+1)
        self.answers.add(answer)
        self.answers.rowCount += 1


    def initAnswers(self):
        # kouknem jestli ma otazka nastaveny defaultni pocet odpovedi
        if self.defaultAnswers:
            x = 0
            while x < self.defaultAnswers:
                self.addAnswer()
                x += 1


    def getData(self):
        """ vrati komplet otazku v GIFT formatu """

        # text otazky
        questionText = self.getQuestion()
        # nazev otazky
        questionTitle = self.getQuestionTitle()
        out = QtCore.QString("%1%2 {").arg(questionTitle).arg(questionText)
        out.append("\n")
        #print type(answer)
        for answer in self.answers:
            # projdem kazdy widget odpovedi a seskladame z toho radek
            answerRow = QtCore.QString()
            # kouknem jestli existuje prefix
            if self.answers.prefix:
                answerRow.append(self.answers.prefix)
            #print answer
            for widget in answer:
                answerRow.append(widget.getValue())
                #print widget
            out.append(QtCore.QString("\t%1").arg(answerRow))
            out.append("\n")
            #out.append("\t%1\n").arg("".join([str(x.getValue()) for x in answer]))
            #for widget in answer:
                #print widget.getValue()
        out.append(QtCore.QString("}"))
        out.append("\n")

        return out


    @QtCore.pyqtSlot()
    def questionPreview(self):
        """ zobrazi nahled otazky v GIFT formatu """

        # otazka v gift formatu
        data = self.getData()
        previewWindow = QtGui.QDialog(self)
        previewWindow.setWindowTitle(self.tr("Question Preview"))
        previewWindowLayout = QtGui.QGridLayout()

        # textEdit pro zobrazeni nahledu
        previewBox = QtGui.QTextEdit(previewWindow)
        previewBox.setReadOnly(True)
        # metoda getData vraci otazku v GIFT formatu, ma ji kazdy typ otazky
        previewBox.setText(data)
        previewWindowLayout.addWidget(previewBox, 0, 0)

        # OK tlacitko na zavreni okna
        previewWindowButonBox = QtGui.QDialogButtonBox()
        previewWindowButonBox.setStandardButtons(QtGui.QDialogButtonBox.Ok)
        previewWindowLayout.addWidget(previewWindowButonBox, 1, 0)

        QtCore.QObject.connect(previewWindowButonBox, QtCore.SIGNAL("accepted()"), previewWindow.close)

        previewWindow.setLayout(previewWindowLayout)
        previewWindow.resize(300, 200)
        previewWindow.show()

        return previewWindow


    def validatePercent(self):
        """ kontrola procentualniho souctu """

        # seznam vsech combo boxu
        comboBoxList = self.ui.answersWidget.findChildren(QtGui.QComboBox)
        # vyfiltrovane pouze ty aktivovane checkboxem
        enabledComboBoxList = [comboBox for comboBox in comboBoxList if comboBox.isEnabled()]
        minusSuma = 0
        plusSuma = 0
        #percentError = False
        # secteme hodnoty
        for comboBox in enabledComboBoxList:
            if comboBox.currentText().toDouble()[0] > 0:
                plusSuma += comboBox.currentText().toDouble()[0]
            elif comboBox.currentText().toDouble()[0] < 0:
                minusSuma += comboBox.currentText().toDouble()[0]

        # pokud soucet hodnot spinboxu presahne 100 nebo -100, pozadi spinboxu se podbarvi cervenou
        if plusSuma > 100 or minusSuma < -100:
            #percentError = True
            # barvime vsechny comboboxy
            for comboBox in comboBoxList:
                comboBox.setStyleSheet("QComboBox:editable { background-color: red }")
        else:
            #if percentError:
            for comboBox in comboBoxList:
                comboBox.setStyleSheet("QComboBox:editable { background-color: white }")
                #percentError = False


    def fillTitle(self, text, title):
        """ vyplnuje text/title otazky """

        # text otazky
        self.ui.question.setText(text)
        # titulek otazky (nazev otazky)
        self.ui.questionTitle.setText(title)


    def basicQuestionValidate(self):
        """ zakladni kontrola validity zapisu otazky """

        if len(self.questionText.toPlainText()) == 0:
            self.errors.append(self.tr("You didn't write text of question."))

        answer0 = self.answersBox.findChild(QtGui.QLineEdit, "answer0")
        if answer0:
            if len(answer0.text()) == 0:
                self.errors.append(self.tr("You must write at least one answer."))


    def getQuestionTitle(self):
        """ vraci nazev otazky, pokud existuje """

        if len(self.ui.questionTitle.text()) != 0:
            questionTitle = "::%s\t::" % self.ui.questionTitle.text()
        else:
            questionTitle = QString()

        return questionTitle


    def getQuestion(self):
        """ vrati zneni otazky """

        return self.ui.question.toPlainText()


    def deleteAnswerRow(self, row):
        """ maže řádek s odpovědí """

        # v row mam cislo radku ktery se bude mazat
        # podle poctu sloupcu radku projdeme vsechny widgety na radku
        for x in range(self.ui.answersLayout.columnCount()):
            widget = self.ui.answersLayout.itemAtPosition(row, x)
            # a smazneme
            if widget is not None:
                self.ui.answersLayout.removeItem(widget)
                widget.widget().setParent(None)

        self.answers.delete(row)
        # TODO
        # nakonec kouknem, jestli je otazka v pohode
        # plati hlavne pro otazky s procenty, kdyz mame 3 odpovedi, s procenty 50, 50, a třeba 3, tak je otazka chybne, po smazani radku s 3% se musi otazka znovu zvalidovat,
        # aby zmizelo cervene zvyrazneni comboboxu s procenty


    def update(self):
        """ vo lam po otevreni otazek ze souboru, aby se nastavil titulek/text otazky, atd """

        self.fillTitle(self.text, self.title)
        